package com.sh.ndt.login.dao;

import com.sh.ndt.common.dao.BaseDAO;
import com.sh.ndt.common.DBConstants;
import com.sh.ndt.common.dao.ExecuteStoredProcedure;
import com.sh.ndt.user.mapper.UserMapper;
import com.sh.ndt.user.mapper.UserRoleMapper;
import com.sh.ndt.user.entity.User;
import com.sh.ndt.user.entity.UserRole;
import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.SqlReturnResultSet;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * Implementation of LoginDAOImpl interface
 * 
 * @author Manjula N. Hosadurga
 */
public class LoginDAOImpl extends JdbcDaoSupport  implements LoginDAO {
    
    private List<UserRole> userRoleData;
    private List<User> userData;
    private static Logger logger = Logger.getLogger(LoginDAOImpl.class);

    public LoginDAOImpl()
    {
        logger.debug("************************** LoginDAO DAO: Initialized");
    }
     
    public LoginDAOImpl(JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager)
    {
        try {
            logger.debug("************************** LoginDAO DAO: Initialized ***");
            logger.debug("jdbc Template in logindao: " + this.getDataSource());
        } catch (Exception ex) {
            logger.debug(ex);
        }
        
    }
    
    @Override
    public boolean authenticateUser(String userName)
    {
        return extractUserData(userName);
    }

    @Override
    public User getUserData()
    {
        return userData.get(0);
    }
    
    @Override
    public UserRole getUserRoleData()
    {
        return userRoleData.get(0);
    }
    
    private boolean extractUserData(String userName)
    {
        boolean retVal = false;
        
        SqlParameter sqlParams[] = new SqlParameter[3];
        sqlParams[0] = new SqlReturnResultSet("user_data", new UserMapper());
        sqlParams[1] = new SqlReturnResultSet("user_role_data", new UserRoleMapper());
        sqlParams[2] = new SqlParameter("userName", Types.VARCHAR);
        
        ExecuteStoredProcedure proc = new ExecuteStoredProcedure(getJdbcTemplate().getDataSource(), DBConstants.SP_LOGIN, sqlParams);
        
        // Now supply values for SP's input parameters
        Map inputs = new HashMap();
        inputs.put("userName", userName);
        
        Map results = proc.executeStoredProcs(inputs);
        
        userRoleData = (List<UserRole>)results.get("user_role_data");
        userData = (List<User>)results.get("user_data");
        
        if (userData != null)
        {
            retVal = true;
        }
        
        return retVal;
    }
    
}
